package com.cloud.common.security.handle;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SameTokenInvalidException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cloud.common.core.exception.ProjectException;
import com.cloud.common.core.result.RespEnum;
import com.cloud.common.core.result.Result;
import com.cloud.common.core.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.method.ParameterErrors;
import org.springframework.validation.method.ParameterValidationResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * 全局异常处理器
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * springboot的各组件执行顺序
	 *
	 * 入方向--------->
	 *      过滤器----拦截器----controller advice----aop----controller
	 * 出方向<--------
	 */

	/**
	 * 权限码异常
	 */
	@ExceptionHandler(NotPermissionException.class)
	public Result handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],权限码校验失败[{}]", requestURI, e.getMessage());
		return Result.error("没有访问权限，请联系管理员授权");
	}

	/**
	 * 角色权限异常
	 */
	@ExceptionHandler(NotRoleException.class)
	public Result<?> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],角色权限校验失败[{}]", requestURI, e.getMessage());
		return Result.error("没有访问权限，请联系管理员授权");
	}

	/**
	 * 认证失败
	 */
	@ExceptionHandler(NotLoginException.class)
	public Result<?> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],认证失败[{}],无法访问系统资源", requestURI, e.getMessage());
		return Result.error("认证失败，无法访问系统资源");
	}

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
			HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],不支持[{}]请求", requestURI, e.getMethod());
		return Result.error(e.getMessage());
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],发生未知异常.", requestURI, e);
		return Result.error(e.getMessage());
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public Result<?> handleException(Exception e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],发生系统异常.", requestURI, e);
		return Result.error(e.getMessage());
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return Result.error(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(HandlerMethodValidationException.class)
	public Result<?> handleHandlerMethodValidationException(HandlerMethodValidationException e,HttpServletRequest req) {
		Map<String,String> map=new ConcurrentHashMap<>();
		List<FieldError> results= e.getBeanResults().get(0).getFieldErrors();
		if(CollUtil.isNotEmpty(results)){
			results.forEach(result->{
				String field=result.getField();
				String message=result.getDefaultMessage();
				map.put(field,message);
			});
		}
		log.info("参数异常,请求地址:[{}],错误信息：{}", req.getRequestURL(), JsonUtil.toJsonString(map));
		return Result.error(map);
	}

	/**
	 * desc 处理业务异常
	 *
	 * @param req
	 * @return
	 */
	@ExceptionHandler(ProjectException.class)
	public Result<?> projectException(ProjectException pe, HttpServletRequest req) {
		log.info("业务异常,请求地址:[{}],错误信息：{}", req.getRequestURL(), getErrMsg(pe),pe);
		return Result.error(pe.getProExp(),pe.getErrMsg());
	}

	/**
	 * 获取错误信息
	 */
	private String getErrMsg(ProjectException pe){
		RespEnum proExp=pe.getProExp();
		return StrUtil.isNotBlank(pe.getErrMsg())?pe.getErrMsg():proExp!=null?proExp.getMsg():"";
	}
}
